package com.yonyou.pmclouds.enterprise.process;

import com.yonyou.pmclouds.basecom.bp.processor.MultiProcessor;
import com.yonyou.pmclouds.basecom.bp.processor.SingleProcessor;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.enterprise.entity.EnterpriseQueryParam;
import com.yonyou.pmclouds.enterprise.entity.EnterpriseRoleEnum;
import com.yonyou.pmclouds.enterprise.entity.EnterpriseVO;
import com.yonyou.pmclouds.enterprise.mapper.EnterpriseMapper;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Author chulf
 * @Date 2020/4/15
 * @Description 业主方 企业组织不能重合 校验
 **/
public class EtpOrgUniqueCheckBeforeProcess implements SingleProcessor<EnterpriseVO>, MultiProcessor<EnterpriseVO> {

    private EnterpriseMapper mapper;
    public EtpOrgUniqueCheckBeforeProcess(EnterpriseMapper mapper){
        this.mapper = mapper;
    }

    @Override
    public void process(EnterpriseVO vo, EnterpriseVO orig) throws BusinessException {

        if (orig != null) {
            if (vo.getRole() == orig.getRole()) return;
        }

        checkRole(new EnterpriseVO[]{vo});

    }

    @Override
    public void process(EnterpriseVO[] vos, EnterpriseVO[] origs) throws BusinessException {
        checkRole(vos);
    }

    private void checkRole(EnterpriseVO[] vos) throws BusinessException {
        if(vos == null || vos.length <= 0){
            return;
        }

        EnterpriseQueryParam enterpriseQueryParam = new EnterpriseQueryParam();
        enterpriseQueryParam.setTenantId(RuntimeEnvironment.getTenantId());
        EnterpriseVO[] enterpriseVOS = mapper.selectEtpsByCondition(enterpriseQueryParam);

        Set<String> pkOrgSet = new HashSet<>();
        for (EnterpriseVO enterpriseVO : enterpriseVOS) {
            if (enterpriseVO.getRole() == EnterpriseRoleEnum.PROPRIETOR.getValue().byteValue()) pkOrgSet.addAll(enterpriseVO.getPkOrgs());
        }

        for(EnterpriseVO enterpriseVO : vos){
            if ( enterpriseVO.getRole() != EnterpriseRoleEnum.PROPRIETOR.getValue().byteValue()){
                return;  //不是业主方不用校验
            }

            if (enterpriseVO.getPkOrgs() == null){
                return;
            }

            List<String> orgArray = enterpriseVO.getPkOrgs();
            for(String pkOrg : orgArray){
                if(pkOrgSet.contains(pkOrg)){
                    throw new BusinessException("该组织下已存在业主方,请修改组织!");
                }
            }
        }
    }
}
